<?php


namespace app\common\service;


/**
 * 基础服务
 */
trait ServiceBase{
    /**
     * 获取前缀
     * @param $name
     * @return bool|mixed
     */
    public static function getLayerPrefix($name){

        $layer = false;

        $layer_array = [LAYER_MODEL_NAME, LAYER_VALIDATE_NAME,LAYER_LOGIC_NAME,LAYER_SERVICE_NAME];

        foreach ($layer_array as $v) {

            if (strpos($name,$v) !== false) {

                $layer = $v;

                break;

            }

        }

        return $layer;

    }
    /**
     * 魔术方法
     * @param $name
     * @param $args
     * @return object|\think\App
     */
    public static function __callStatic($name,$args){

        $layer = self::getLayerPrefix($name);

        empty($layer) && abort(403,LAYER_LOGIC_NAME.'层中魔术方法使用前缀错误');

        $instanceName = $args[0];

        $instance = parseClass($instanceName,$layer);

        return app($instance);

    }

    /**
     * 错误终止程序
     */
    public static function commonError($code_data = [])
    {

        !isset($code_data['success']) && $code_data['success'] = false;

        if ($code_data['code'] < 1000) {#其余的提示是大于1000000的

            ServiceBase::throwHttpCode($code_data);

        } else {

            return throw_response_exception($code_data);

        }

    }

    /**
     * 中断并返回http协议错误
     * @param string $code [description]
     * @return [type]       [description]
     */
    public static function throwHttpCode($code_data = '')
    {

        $code = $code_data['code'];

        $error = !empty($code_data['msg']) ? $code_data['msg'] : 'success';

        header("HTTP/1.1 " . $code . " " . $error);

        header("Content-Type:application/json;charset=utf-8");

        exit(json_encode($code_data, JSON_UNESCAPED_UNICODE));
    }
}
